/**
 * 
 */
package com.jsync.system;

import com.jsync.events.SFTPSyncTrigger;
import com.jsync.events.WindowsSyncTrigger;
import com.jsync.model.Resource;
import com.jsync.model.ResourceProfile;
import com.jsync.model.ResourceQueue;
import com.jsync.model.ResourceType;
import com.jsync.service.ResourceQueueManager;
import com.jsync.util.SingletonFactory;


/**
 * @author prabz
 *
 */
public class ResourceMonitor implements Runnable {
	
	private Long sleepTime;
	private boolean stopFlag;
	private ResourceProfile profile;
	private WindowsFileListener wfl;
	private WindowsSyncTrigger wst;
	private SFTPSyncTrigger sst;
	
	/**
	 * @return the sleepTime
	 */
	public Long getSleepTime() {
		return sleepTime;
	}

	/**
	 * @param sleepTime the sleepTime to set
	 */
	public void setSleepTime(Long sleepTime) {
		this.sleepTime = sleepTime;
	}

	/**
	 * @return the stopFlag
	 */
	public boolean isStopFlag() {
		return stopFlag;
	}

	/**
	 * @param stopFlag the stopFlag to set
	 */
	public void setStopFlag(boolean stopFlag) {
		this.stopFlag = stopFlag;
	}

	/**
	 * @return the profile
	 */
	public ResourceProfile getProfile() {
		return profile;
	}

	/**
	 * @param profile the profile to set
	 */
	public void setProfile(ResourceProfile profile) {
		this.profile = profile;
	}

	public ResourceMonitor(){
		setSleepTime(2000l);
		setStopFlag(false);
		wfl = (WindowsFileListener)SingletonFactory.getInstance().get(WindowsFileListener.class);
		wst = (WindowsSyncTrigger)SingletonFactory.getInstance().get(WindowsSyncTrigger.class);
		sst = (SFTPSyncTrigger)SingletonFactory.getInstance().get(SFTPSyncTrigger.class);
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		if(profile==null)
			return;
		
		// Watch all the profiles		
		if(profile.getSourceType().equals(ResourceType.WINDOWS)){
			wfl.watch(profile);				
		}
		
		// Process the Queue
		//ResourceQueue rq = (ResourceQueue) SingletonFactory.getInstance().get(ResourceQueue.class);
		ResourceQueueManager rqm = (ResourceQueueManager) SingletonFactory.getInstance().get(ResourceQueueManager.class);
		ResourceQueue rq = rqm.createResourceQueue(profile);
		try{
			while(!isStopFlag()){
				// Read from queue
				if(!rq.isEmpty()){
					Resource resource = rq.removeFirst();
					if(ResourceType.WINDOWS.equals(resource.getProfile().getDestType())){
						wst.send(resource);
					}else if(ResourceType.SFTP.equals(resource.getProfile().getDestType())){
						sst.send(resource);
					}
				}
				Thread.sleep(sleepTime);
			}			
		}catch(InterruptedException ex){
			ex.printStackTrace();
		}
	}
}